import { Component, Inject, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { MessageService } from 'primeng/api';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  providers: [MessageService],
})
export class HomeComponent implements OnInit {
  isShowEdit: boolean = false;
  list: DaMaiConfig[] = [];
  row!: DaMaiConfig;

  private defaultRow: DaMaiConfig = {
    id: 0,
    description: '戴佩妮1',
    name: '戴佩妮',
    region: '广州',
    dateTime: '2023-10-21  周六 20:00',
    price: '980元',
    ticket: 2,
    user: '黄泽铿,黄燕卿',
    pay: '微信',
    doOrder: '否',
    execTime: '2023-08-27 21:34:00',
  };

  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string, private messageService: MessageService) {}

  ngOnInit(): void {
    this.getList();
  }

  handleClickAdd() {
    this.row = { ...this.defaultRow };
    this.isShowEdit = true;
  }

  handleClickUpdate(item: DaMaiConfig) {
    this.row = { ...this.defaultRow, ...item };
    this.isShowEdit = true;
  }

  handleClickDelete(item: DaMaiConfig) {
    this.http.get<ApiResult>(this.baseUrl + `api/DaMai/Delete?id=${item.id}`).subscribe(result => {
      if (result.code == 200) {
        this.messageService.add({ severity: 'success', summary: 'Success', detail: result.message });
        this.getList();
      } else {
        this.messageService.add({ severity: 'error', summary: 'Error', detail: result.message });
      }
    });
  }

  handleClickSave() {
    this.http.post<ApiResult>(this.baseUrl + `api/DaMai/Save`, this.row).subscribe(result => {
      if (result.code == 200) {
        this.messageService.add({ severity: 'info', summary: 'Info', detail: result.message });
        this.getList();
        this.isShowEdit = false;
      } else {
        this.messageService.add({ severity: 'error', summary: 'Error', detail: result.message });
      }
    });
  }

  getList() {
    this.http.get<DaMaiConfig[]>(this.baseUrl + 'api/DaMai/GetList').subscribe(result => {
      this.list = result;
    });
  }
}

interface ApiResult {
  code: number;
  message: string;
}

interface DaMaiConfig {
  id: number;
  description: string;
  name: string;
  region: string;
  dateTime: string;
  price: string;
  ticket: number;
  user: string;
  pay: string;
  doOrder: string;
  execTime: string;
}
